package cn.com.libertymutual.sp.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.bean.TbSpSaveData;
import cn.com.libertymutual.sp.dao.SaveDataDao;
import cn.com.libertymutual.sp.service.api.SaveDataService;

@Service("SaveDataService")
public class SaveDataServiceImpl implements SaveDataService {

	@Autowired
	private SaveDataDao saveDataDao;
	@Resource
	private RestTemplate restTemplate;
	@Autowired
	private JdbcTemplate readJdbcTemplate;

	@Override
	public ServiceResult createSaveData(TbSpSaveData saveData) {
		ServiceResult sr = new ServiceResult();
		saveData.setCreateTime(new Date());
		sr.setSuccess();
		try {
			saveDataDao.save(saveData);
		} catch (Exception e) {
			sr.setFail();
		}
		return sr;
	}

	@Override
	public ServiceResult findUserSaveData(Integer pageNumber, Integer pageSize, String userCode, String riskCode) {
		ServiceResult sr = new ServiceResult();
		pageNumber = (pageNumber - 1) * pageSize;
		if (pageNumber != 0) {
			pageSize = pageNumber * pageSize;
		}
		String sql = "select d.ID as id,d.PRICE as price, d.MARK_TEXT as mark,d.RISK_CODE as  riskCode, d.STATE as state ,DATE_FORMAT(d.START_TIME, '%Y-%c-%d %H:%i:%s') as stTime,DATE_FORMAT(d.END_TIME, '%Y-%c-%d %H:%i:%s') as endTime,DATE_FORMAT(d.CREATE_TIME, '%Y-%c-%d %H:%i:%s') as createTime from tb_sp_save_data as d where RISK_CODE=? and USER_CODE=? ORDER BY CREATE_TIME desc LIMIT ?,?";
		List<Map<String, Object>> list = readJdbcTemplate.queryForList(sql, new Object[] { riskCode, userCode, pageNumber, pageSize });
		sr.setSuccess();
		sr.setResult(list);
		// TODO Auto-generated method stub
		return sr;
	}

	@Override
	public ServiceResult findSaveDataId(Integer id) {
		ServiceResult sr = new ServiceResult();

		TbSpSaveData saveData = saveDataDao.findSaveDataId(id);
		if (saveData == null) {
			sr.setFail();
		} else {
			sr.setSuccess();
			sr.setResult(saveData);
		}
		return sr;
	}

}
